﻿using DataProcess.Interface;
using DataProcess.Interface.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace DataProcessing.BangXinWeiYeXRF
{
    public class DataProcessing : IDataProcessing
    {
        public string Name { get { return "邦鑫伟业荧光仪"; } }

        public IDataOutput Processing(string content)
        {
            if (!content.StartsWith("@") || !content.EndsWith("$")) return null;
            if (!content.Contains("SampleID")) return null;

            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            foreach (var str in content.TrimStart('@').TrimEnd('$').Split(','))
            {
                var pair = str.Split('=');
                if (pair.Length == 2)
                {
                    if (keyValues.ContainsKey(pair[0].Trim()))
                    {
                        keyValues[pair[0].Trim()] = pair[1];
                    }
                    else
                    {
                        keyValues.Add(pair[0].Trim(), pair[1]);
                    }
                }
            }

            XRayOutputModel outputModel = new XRayOutputModel();

            outputModel.SampleName = keyValues["SampleID"].Trim();
            keyValues.Remove("SampleID");
            outputModel.AnalyzeApplicationName = keyValues.ContainsKey("Workzone") ? keyValues["Workzone"] : "Unknow";
            keyValues.Remove("Workzone");
            if (keyValues.ContainsKey("Time"))
            {
                if (DateTime.TryParse(keyValues["Time"].Trim(), out DateTime date))
                {
                    outputModel.MeasureTime = date;
                }
                else
                {
                    outputModel.MeasureTime = DateTime.Now;
                }
                keyValues.Remove("Time");
            }
            else
            {
                outputModel.MeasureTime = DateTime.Now;
            }

            for (int i = 0; i < keyValues.Count; i++)
            {
                var kv = keyValues.ElementAt(i);
                var match = Regex.Match(kv.Value, @"\d+(\.\d+)");
                if (match.Success)
                {
                    keyValues[kv.Key] = match.Value;
                }
            }

            outputModel.Eelements = keyValues;

            return outputModel;
        }
    }
}
